#include "child_socket_worker.h"
#include "include.h"

child_socket_worker::child_socket_worker(uv_loop_t* loop,int num)
{
    this->loop=loop;
    this->num=num;
    args[0]=(char*)DEFAULTWORKERPATH;
    args[1]=NULL;
}

auto* child_socket_worker::getProcessHandle (){
    return &(this->process);
}

auto* child_socket_worker::getReadPipeHandle (){
    return &(this->piper);
}

auto* child_socket_worker::getWritePipeHandle (){
    return &(this->pipew);
}

auto* child_socket_worker::getProcessOptionsHandle (){
    return &(this->process_options);
}

auto child_socket_worker::getNum(){
    return this->num;
}

auto* child_socket_worker::getStdioContainer (){
    return this->stdio_container;
}

auto child_socket_worker::getPid (){
    return this->pid;
}

auto child_socket_worker::buildDefault (){
    uv_pipe_init(this->loop,&(this->piper),1);
    uv_pipe_init(this->loop,&(this->pipew),1);
    this->stdio_container[0].flags=uv_stdio_flags(UV_CREATE_PIPE|UV_READABLE_PIPE);
    this->stdio_container[0].data.stream=(uv_stream_t*)&(this->piper);
    this->stdio_container[1].flags=uv_stdio_flags(UV_CREATE_PIPE|UV_WRITABLE_PIPE);
    this->stdio_container[1].data.stream=(uv_stream_t*)&(this->pipew);
    this->stdio_container[2].flags=UV_INHERIT_FD;
    this->stdio_container[2].data.fd=2;
    this->process_options.exit_cb=this->exitCallback;
    this->process_options.stdio=this->stdio_container;
    this->process_options.stdio_count=3;
    this->process_options.file=this->args[0];
    this->process_options.args=this->args;
}

auto child_socket_worker::setExitCallback(uv_exit_cb exitCallback){
    this->exitCallback=exitCallback;
}

auto child_socket_worker::run(){
    uv_spawn(this->loop,&(this->process),&(this->process_options));
    pid=this->process.pid;
}

auto child_socket_worker::stop (){
    kill(this->pid,SIGKILL);
}
